package com.xiaouyudeguang.common.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.xiaouyudeguang.common.constants.Headers;
import com.xiaouyudeguang.common.utils.EnvironmentUtils;
import com.xiaouyudeguang.common.utils.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.env.Environment;

import java.text.SimpleDateFormat;

/**
 * <p>
 * 容器工具类
 * </p>
 *
 * @author 赵光
 * @since 2018年11月27日
 */
@Configuration
@EnableAspectJAutoProxy
@ComponentScan("io.gitee.xiaouyudeguang.common")
public class AppConfig implements CommandLineRunner {

    private static Environment environment;

    public AppConfig(@Autowired Environment environment) {
        AppConfig.environment = environment;
    }

    public static Environment getEnv() {
        return environment;
    }

    @Bean
    @ConditionalOnMissingBean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 反序列化时忽略不存在的属性
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 序列化时将LocalDateTime转换为时间戳格式
        objectMapper.registerModule(new JavaTimeModule());
        return objectMapper;
    }

    @Override
    public void run(String... args) throws Exception {
        MDC.put(Headers.TRACE_ID, StringUtils.getOrDefault(EnvironmentUtils.getNamespace(), environment.getProperty("spring.application.name")));
    }
}
